#include <board.h>
#include <board_memories.h>
#include <tsd/tsd.h>
#include <tsd/inarea.h>
#include <lcd/lcdd.h>
#include <lcd/draw.h>
#include <pit/pitd.h>
#include <pio/pio.h>
#include <memories/MEDSdcard.h>

static unsigned char *_lcd_buffer = (unsigned char *) (AT91C_EBI_SDRAM + 0x01000000);

#define W   100
#define H   70

inarea_rect_t topleft [1] = {{ .x = 0, .y = 0, .width = W, .height = H}};
inarea_rect_t bottomright [1] = {{ .x = BOARD_LCD_WIDTH - W, .y = BOARD_LCD_HEIGHT - H, .width = W, .height = H}};
inarea_rect_t cross [3] = {
    { .x = W, .y = 0, .width = BOARD_LCD_WIDTH - 2*W, .height = H},
    { .x = W, .y = BOARD_LCD_HEIGHT - H, .width = BOARD_LCD_WIDTH - 2*W, .height = H},
    { .x = 0, .y = H, .width = BOARD_LCD_WIDTH, .height = BOARD_LCD_HEIGHT - 2*H}
};

void prs(inarea_rect_t* id) {
    if (id == topleft) {
        LCDD_DrawCircle(_lcd_buffer, BOARD_LCD_WIDTH - 20, 20, 13, COLOR_OLIVE);
    } else if (id == bottomright) {
        LCDD_DrawCircle(_lcd_buffer, BOARD_LCD_WIDTH - 20, 20, 13, COLOR_GREENYELLOW);
    } else if (id == cross) {
        LCDD_DrawCircle(_lcd_buffer, BOARD_LCD_WIDTH - 20, 20, 13, COLOR_SKYBLUE);
    }
}

void mvo(inarea_rect_t* id) {
    if (id == topleft) {
        LCDD_DrawCircle(_lcd_buffer, BOARD_LCD_WIDTH - 20, 20, 13, COLOR_BROWN);
    } else if (id == bottomright) {
        LCDD_DrawCircle(_lcd_buffer, BOARD_LCD_WIDTH - 20, 20, 13, COLOR_GOLD);
    } else if (id == cross) {
        LCDD_DrawCircle(_lcd_buffer, BOARD_LCD_WIDTH - 20, 20, 13, COLOR_VIOLET);
    }
}

void rls(inarea_rect_t* id) {
    LCDD_DrawCircle(_lcd_buffer, BOARD_LCD_WIDTH - 20, 20, 13, COLOR_WHITE);
}

int main() {

    // Initialize LCD
    LCDD_Fill(_lcd_buffer, COLOR_WHITE);
    LCDD_Initialize();
    LCDD_DisplayBuffer(_lcd_buffer);

#if !defined(sdram)
    BOARD_ConfigureSdram(BOARD_SDRAM_BUSWIDTH);
#endif

    TSD_Initialize(0);
    PITD_Configure(TSD_Update_PenState, 10000, 0);
    TSD_SetPitPeriod(10);
    PITD_Start();
    while (!TSD_Calibrate(_lcd_buffer))
        ;
    PITD_Stop();

    LCDD_DrawRectangle(_lcd_buffer,
            topleft[0].x, topleft[0].y,
            topleft[0].width, topleft[0].height,
            COLOR_OLIVE);

    LCDD_DrawRectangle(_lcd_buffer,
            bottomright[0].x, bottomright[0].y,
            bottomright[0].width, bottomright[0].height,
            COLOR_GREENYELLOW);

    LCDD_DrawRectangle(_lcd_buffer,
            cross[0].x, cross[0].y,
            cross[0].width, cross[0].height,
            COLOR_SKYBLUE);
    LCDD_DrawRectangle(_lcd_buffer,
            cross[1].x, cross[1].y,
            cross[1].width, cross[1].height,
            COLOR_SKYBLUE);
    LCDD_DrawRectangle(_lcd_buffer,
            cross[2].x, cross[2].y,
            cross[2].width, cross[2].height,
            COLOR_SKYBLUE);

    TSD_InareaAdd(prs, mvo, rls, cross, 3);
    TSD_InareaAdd(prs, mvo, rls, topleft, 1);
    TSD_InareaAdd(prs, mvo, rls, bottomright, 1);

    PITD_Start();
    return 0;
}
